﻿<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="temp"
      label-position="right"
      label-width="200px"
      style="width: 400px margin:auto"
      size="small"
    >
      <el-form-item :label="$t('order.username')+' :'">
        <span>{{ username }}</span>
      </el-form-item>
      <el-form-item :label="$t('charge.type')+' :'">
        <el-button
          v-if="permission.recharge"
          class="filter-item"
          type="primary"
          style="margin-left:20px"
          :disabled="type===3?true:false"
          @click="changeType(3)"
        >转账</el-button>
        <el-button
          v-if="permission.recharge"
          class="filter-item"
          type="primary"
          style="margin-left:20px"
          :disabled="type===4?true:false"
          @click="changeType(4)"
        >现金</el-button>
        <el-button
          v-if="permission.Barter"
          class="filter-item"
          type="primary"
          style="margin-left:20px"
          :disabled="type===5?true:false"
          @click="changeType(5)"
        >易物</el-button>
      </el-form-item>
      <template v-if="type === 3">
        <el-form-item :label="$t('charge.name')+' :'" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('charge.account')+' :'" prop="account">
          <el-input v-model="temp.account"></el-input>
        </el-form-item>
        <el-form-item :label="$t('charge.bankName')+' :'" prop="bank_name">
          <el-input v-model="temp.bank_name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('charge.transferAmount')+' :'" prop="money">
          <el-input-number v-model="temp.money" style="width:185px"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('charge.picture')+' :'" prop="picture">
          <el-input v-model="temp.picture" style="display:none"></el-input>
          <li
            v-if="temp.picture"
            tabindex="0"
            class="el-upload-list__item is-success"
            style="width:150px;height:auto;display:block;padding: 0 5px;"
          >
            <img
              :src="temp.picture"
              alt
              class="el-upload-list__item-thumbnail"
              style="width:100%;height:auto"
            />
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check"></i>
            </label>
            <i class="el-icon-close" @click="changPicture('picture')"></i>
            <i class="el-icon-close-tip"></i>
          </li>
          <el-upload
            v-else
            v-loading="pictureLoading"
            action="#"
            class="avatar-uploader"
            :http-request="(e)=>{return updatePicture(e,'picture', 'pictureLoading')}"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('public.remark')+' :'" prop="remark" style="width:600px">
          <el-input v-model="temp.remark" type="textarea"></el-input>
        </el-form-item>
      </template>
      <template v-if="type === 4">
        <el-form-item :label="$t('charge.name')+' :'" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('charge.transferAmount')+' :'" prop="money">
          <el-input-number v-model="temp.money" style="width:185px"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('charge.dealTime')+' :'" prop="deal_time">
          <el-date-picker
            v-model="temp.deal_time"
            type="date"
            :placeholder="$t('charge.dealTime')"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="endDatePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('public.remark')+' :'" prop="remark" style="width:600px">
          <el-input v-model="temp.remark" type="textarea"></el-input>
        </el-form-item>
      </template>
      <template v-if="type === 5">
        <el-form-item :label="$t('order.productName')+' :'" prop="goods_id">
          <select-value
            :id="temp.goods_id"
            :name="temp.goods_name"
            style="width:200px"
            placeholder="请选择商品"
            :data="goodOptions"
            :count="goodCount"
            :page-size="pageSize"
            key-field="id"
            show-field="name"
            @getList="getGoodList"
            @values="getGoodid"
          ></select-value>
        </el-form-item>
        <el-form-item :label="$t('order.num')+' :'" prop="num">
          <el-input-number v-model="temp.num" :min="1" :max="10000000" style="width:185px"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('order.exchangeValue')+' :'">
          <el-input v-model="sumValue" disabled></el-input>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button
          v-if="type === 5 || type === 3 || type === 4"
          native-type="reset"
        >{{ $t('table.refresh') }}</el-button>
        <el-button
          v-if="type === 5 || type === 3 || type === 4"
          type="primary"
          :disabled="!updateDisabled"
          @click="barterData"
        >{{ $t('table.confirm') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import selectValue from "@/views/select/SelectValue"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
  name: "Recharge",
  components: {
    "select-value": selectValue
  },
  data() {
    const bankAccountNumber = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        var reg = /^([1-9]{1})(\d{14}|\d{18})$/; /* 银行卡号验证 */
        if (reg.test(value)) {
          /* 进行验证 */
          callback();
        } else {
          callback(new Error("请输入正确的付款账户！"));
        }
      } else {
        callback(new Error("请填写付款账户！"));
      }
    };
    const money = (rule, value, callback) => {
      if (value || value === 0) {
        if (value > 0 && value < 10000000) {
          callback();
        } else {
          callback(new Error("充值金额只能是1-10000000！"));
        }
      } else {
        callback(new Error("请填写金额！"));
      }
    };
    const remark = (rule, value, callback) => {
      if (value) {
        if (value.length > 150) {
          callback(new Error("备注信息不能超过150个字符"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入备注信息"));
      }
    };
    const name = (rule, value, callback) => {
      if (value) {
        if (value.length > 10) {
          callback(new Error("收款人名称不能超过10个字符"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入收款人名称"));
      }
    };
    const bank_name = (rule, value, callback) => {
      if (value) {
        if (value.length > 20) {
          callback(new Error("开户行名称不能超过20个字符"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请填写开户行名称"));
      }
    };
    return {
      endDatePicker: this.processDate(),
      showSearchItem: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      userid: "",
      username: "",
      type: "",
      typeOptions: [
        {
          value: 1,
          label: "微信"
        },
        {
          value: 2,
          label: "支付宝"
        },
        {
          value: 3,
          label: "转账"
        },
        {
          value: 4,
          label: "现金"
        },
        {
          value: 5,
          label: "易物"
        }
      ],
      temp: {
        id: undefined,
        goods_id: undefined,
        goods_name: "",
        set_price: "",
        num: "",
        type: "",
        name: "",
        deal_time: "",
        account: "",
        bank_name: "",
        picture: "",
        money: undefined,
        remark: ""
      },
      pictureLoading: "",
      dialogFormVisible: false,
      upLoading: false,
      rules: {
        name: [{ required: true, trigger: "blur", validator: name }],
        deal_time: [
          { required: true, message: "请选择付款时间", trigger: "change" }
        ],
        account: [
          { required: true, trigger: "blur", validator: bankAccountNumber }
        ],
        bank_name: [
          { required: true, trigger: "blur", validator: bank_name }
        ],
        picture: [
          { required: true, message: "请上传转账凭证", trigger: "change" }
        ],
        money: [{ required: true, trigger: "blur", validator: money }],
        remark: [{ required: true, trigger: "blur", validator: remark }],
        goods_id: [
          { required: true, message: "请选择兑换商品", trigger: "change" }
        ],
        num: [{ required: true, message: "请填写兑换数量", trigger: "blur" }]
      },
      textMap: {
        update: "更新",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      updateDisabled: true,
      loading: false,
      goodOptions: [],
      goodCount: undefined,
      pageSize: 20,
      permission: {
        recharge: false,
        Barter: false
      }
    };
  },
  computed: {
    sumValue: function() {
      if (this.temp.num && this.temp.set_price) {
        return this.temp.num * this.temp.set_price;
      } else {
        return 0;
      }
    }
  },
  created() {
    if (this.$store.state.permission.jurisdiction === "*") {
      this.permission.recharge = true;
      this.permission.Barter = true;
    } else {
      const jurisdiction = this.$store.state.permission.jurisdiction.split(",");
      jurisdiction.forEach(element => {
        const id = parseInt(element);
        if (id === 211) {
          this.permission.recharge = true;
        }
        if (id === 210) {
          this.permission.Barter = true;
        }
      });
    }
    if(JSON.parse(getToken()).username){
      this.username = JSON.parse(getToken()).username;
    }else{
      this.username = JSON.parse(getToken()).name;
    }
  },
  methods: {
    processDate() {
      return {
        disabledDate(time) {
          return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
        }
      };
    },
    getGoodList(pageNumber = 1, search = "") {
      this.getGood(pageNumber, search);
    },
    getGoodid(data) {
      if (data.length > 0) {
        this.temp.goods_id = data[0].id;
        this.temp.goods_name = data[0].name;
        this.temp.set_price = data[0].value;
      } else {
        this.temp.goods_id = undefined;
        this.temp.goods_name = "";
        this.temp.set_price = "";
      }
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        goods_id: undefined,
        goods_name: "",
        set_price: "",
        num: "",
        type: "",
        name: "",
        deal_time: "",
        account: "",
        bank_name: "",
        picture: "",
        money: undefined,
        remark: ""
      };
    },
    barterData() {
      // 充值
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            let data = {};
            let OrderCreatePath = {};
            if (this.type === 5) {
              // 易物充值
              data = {
                goods_id: this.temp.goods_id,
                num: this.temp.num
              };
              OrderCreatePath = {
                company: "STQ",
                api: "pc_order_orderCreate",
                version: "1.0",
                data: data
              };
            } else if (this.type === 4) {
              // 现金充值
              data = {
                type: "1",
                name: this.temp.name,
                deal_time: this.temp.deal_time,
                money: this.temp.money,
                remark: this.temp.remark
              };
              OrderCreatePath = {
                company: "STQ",
                api: "pc_order_recharge",
                version: "1.0",
                data: data
              };
            } else if (this.type === 3) {
              // 转帐充值
              data = {
                type: "2",
                name: this.temp.name,
                account: this.temp.account,
                bank_name: this.temp.bank_name,
                picture: this.temp.picture,
                money: this.temp.money,
                remark: this.temp.remark
              };
              OrderCreatePath = {
                company: "STQ",
                api: "pc_order_recharge",
                version: "1.0",
                data: data
              };
            }
            this.socketApi.sendSock(JSON.stringify(OrderCreatePath), res => {
              if (res) {
                this.socketData(res);
              } else {
                this.$message.error(" 审核失败 ");
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    // 商品查询
    getGood(pageNumber, search) {
      const goodsIndexPath = {
        company: "STQ",
        api: "pc_goods_index",
        version: "1.0",
        data: {
          goods_name: search,
          page: pageNumber,
          rows: this.pageSize,
          type: 2
        }
      };
      this.socketApi.sendSock(JSON.stringify(goodsIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    getEquipment(pageNumber, search) {
      const getEquipmentCodePath = {
        company: "STQ",
        api: "pc_equipment_getEquipmentCode",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(getEquipmentCodePath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    updatePicture(element, name, loading) {
      this[loading] = true;
      const video = new FormData();
      video.append("video", element.file);

      this.updateFile(video, result => {
        if (result.data.code === 0) {
          this.$message.error(result.data.message);
        } else {
          this.temp[name] = result.data.data.video_url;
        }
        this[loading] = false;
      });
    },
    changPicture(name) {
      this.$confirm("是否删除该图片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const index = this.temp[name].lastIndexOf("/");
          const str = this.temp[name].substring(
            index + 1,
            this.temp[name].length
          );
          const video_name = { video_name: str };
          this.deleteFile(video_name, result => {
            if (result.data.code === 0) {
              this.$message.error(result.data.message);
            } else {
              this.temp[name] = "";
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    changeType(type) {
      this.type = type;
      this.resetTemp();
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "pc_order_index") {
            // 充值列表
            this.total = resj.count;
            this.list = resj.data;
          } else if (resj.api === "pc_order_orderCreate") {
            // 充值审核
            this.$notify({
              title: "成功",
              message: "充值成功",
              type: "success",
              duration: 2000
            });
            this.resetTemp();
            this.$nextTick(() => {
              this.$refs["dataForm"].clearValidate();
            });
          } else if (resj.api === "pc_goods_index") {
            const options = [];
            resj.data.forEach(element => {
              options.push({
                id: element.goods_id,
                name: element.goods_name,
                value: element.set_price
              });
            });
            this.goodOptions = options;
            this.goodCount = resj.count;
          } else if (resj.api === "pc_order_recharge") {
            // 转账充值
            this.$notify({
              title: "成功",
              message: "充值成功",
              type: "success",
              duration: 2000
            });
            this.resetTemp();
            this.$nextTick(() => {
              this.$refs["dataForm"].clearValidate();
            });
          }
        }
      }
    }
  }
};
</script>
